﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharePointOfView.WebControls;
using System.IO;
using Microsoft.SharePoint;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;

namespace SharePointOfView.Samples.WebControls
{
    /// <summary>This sample WebPart shows how to use SharePointOfView XslTransform WebPart.</summary>
    /// <remarks>You need both to implement GetData method and to provide an XSLT string.</remarks>
    public class CAMLQueryWebPart : XslTransformWebPart
    {
        #region Private statements

        private string _listUrl = SPContext.Current.Web.Url + "/Lists/Tasks/AllItems.aspx";
        private SPQuery _camlQuery = null;

        #endregion

        #region Public properties

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("List URL"),
        WebDescription("URL of the list to query. The list has to be linked to the current web."),
        Category("SharePointOfView")]
        public string ListURL
        {
            get
            {
                return _listUrl;
            }
            set
            {
                _listUrl = value;
            }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("CAML Query"),
        WebDescription("CAML Query used to filter the list."),
        Category("SharePointOfView")]
        public string CAMLQuery
        {
            get
            {
                if (_camlQuery == null)
                {
                    _camlQuery = new SPQuery();
                }
                return _camlQuery.Query;
            }
            set
            {
                if (_camlQuery == null)
                {
                    _camlQuery = new SPQuery();
                }
                _camlQuery.Query = value;
            }
        }

        #endregion

        /// <summary>Filter the list by applying the provided CAML Query</summary>
        /// <returns>The XML formatted result of the query.</returns>
        protected override string GetData()
        {
            if (CAMLQuery != null)
            {
                SPList list = SPContext.Current.Web.GetListFromUrl(ListURL);
                return list.GetItems(_camlQuery).Xml;
            }
            return base.GetData();
        }
    }
}
